// 页面职责: 所有公共处理的方法和业务没关系 就是移到任意一个项目都能用的代码放这里
import moment from '@/lib/moment/moment.min.js'
import parseHtml from "@/lib/common/html-parser.js";

let moveFunction = (e) => {
	e.preventDefault();
}

function wxCanMove(isCanMove = false) {
	//禁止页面拖动
	if (!isCanMove) {
		document.addEventListener('touchmove', moveFunction, {
			passive: false
		});
	} else {
		document.removeEventListener('touchmove', moveFunction);
	}
}

function getDistanceKm(lat1, lon1, lat2, lon2) {
	lat1 = Number(lat1);
	lon1 = Number(lon1);
	lat2 = Number(lat2);
	lon2 = Number(lon2);
	var R = 6371; // 地球半径，单位千米
	var dLat = (lat2 - lat1) * (Math.PI / 180);
	var dLon = (lon2 - lon1) * (Math.PI / 180);
	var lat1 = lat1 * (Math.PI / 180);
	var lat2 = lat2 * (Math.PI / 180);

	var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
		Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
	var d = R * c;
	if (d > 1000) d = 999;
	return d.toFixed(1);
}


function isAndriod() {
	var UA = window.navigator.userAgent.toLowerCase();
	var isAndroid = UA.indexOf('android') > 0;
	return isAndroid;
}

function isIos() {
	var UA = window.navigator.userAgent.toLowerCase();
	return /iphone|ipad|ipod|ios/.test(UA);
}

// 计算属相
function deepCopy(data) {
	return JSON.parse(JSON.stringify(data));
}

// 调用上个页面的方法
function getPrePageObj(keyName, data, index = 2) {
	const pages = getCurrentPages(); //当前页
	const beforePage = pages[pages.length - index]; //上个页面
	// #ifdef H5
	if (beforePage) {
		if (typeof beforePage[keyName] == 'function') {
			return beforePage[keyName](data);
		} else {
			return beforePage[keyName];
		}
	}

	// #endif
	// #ifndef H5
	beforePage.$vm[keyName](data);
	// #endif
}

// 计算属相
function calAge(date) {
	if (date) {
		return moment().diff(date, 'years');
	}
}


// 计算属相
function calAnimalSign(date) {
	if (date) {
		let year = moment(date).format('YYYY');
		let arr1 = ['猴', '鸡', '狗', '猪', '鼠', '牛', '虎', '兔', '龙', '蛇', '马', '羊'];
		return /^\d{4}$/.test(year) ? arr1[year % 12] : '无';
	}
}


// 计算星座
function calStar(date) {
	if (date) {
		let month = moment(date).format('MM');
		let day = moment(date).format('DD');
		let s = "魔羯水瓶双鱼白羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯";
		let arr2 = [20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22];
		let result2 = s.substr(month * 2 - (day < arr2[month - 1] ? 2 : 0), 2);
		return result2
	}
}

function showImg(urls, current) {
	uni.previewImage({
		urls: urls,
		current: current
	});
}
/**
 * @description: 对象转url参数
 * @paramObj {Object} obj数据
 * @valDealFunc {值的处理默认是url加密}
 */
function urlEncode(paramObj, valDealFunc = val => encodeURIComponent(val)) {
	if (typeof(paramObj) != 'object') return '';
	const urlDatas = [];
	for (let key in paramObj) {
		urlDatas.push(`${key}=${valDealFunc(paramObj[key])}`);
	}
	return urlDatas.join('&');
}

/**
 * null => ''
 * @param {*} data 要处理的数据
 */
function null2str(data) {
	for (let x in data) {
		if (data[x] === null) { // 如果是null 把直接内容转为 ''
			data[x] = '';
		} else {
			if (Array.isArray(data[x])) { // 是数组遍历数组 递归继续处理
				data[x] = data[x].map(z => {
					return null2str(z);
				});
			}
			if (typeof(data[x]) === 'object') { // 是json 递归继续处理
				data[x] = null2str(data[x])
			}
		}
	}
	return data;
}

/** 检查哪些属性发生变化时需要刷新
 * @param {Object} newValue
 * @param {Object} oldValue
 * @param {Object} checkFields 需要检查的属性 ['name','age']
 */
function isChgForWatch(newValue, oldValue, checkFields) {
	// 第一次watch
	if (oldValue === undefined) return true;

	// 对比变化
	for (let i = 0; i < checkFields.length; i++) {
		if (oldValue[checkFields[i]] != newValue[checkFields[i]]) {
			return true;
		}
	}

	// 最终返回
	return false;
}


// 获取当前界面和完整参数
function getCurrentPageUrl() {
	let pages = getCurrentPages(); // 获取加载的页面
	let currentPage = pages[pages.length - 1]; // 获取当前页面的对象
	if (currentPage) {
		let url = currentPage.route; // 当前页面url
		return url;
	} else {
		let url = window.location.pathname; // 当前页面url
		return url;
	}
}

// 获取当前页带参数的url
function getCurrentPageUrlAndArgs() {
	let pages = getCurrentPages(); //获取加载的页面
	let currentPage = pages[pages.length - 1]; //获取当前页面的对象
	let url = currentPage.route; //当前页面url
	let options = getQueryObj();

	//拼接url的参数
	let urlWithArgs = url + '?';

	for (let key in options) {
		let value = options[key];
		urlWithArgs += key + '=' + value + '&';
	}

	urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1);
	return urlWithArgs;
}

// 获取url的参数
function getQueryObj() {
	let pages = getCurrentPages(); // 获取加载的页面
	let currentPage = pages[pages.length - 1]; //获取当前页面的对象
	let options = JSON.stringify(currentPage.$page.options) == "{}" ? currentPage.$route.query : currentPage.$page
		.options; //如果要获取url中所带的参数可以查看options
	return options;
}

function isWxBrowser() {
	if (navigator) {
		let ua = navigator.userAgent.toLowerCase();
		let isWeixin = ua.indexOf('micromessenger') != -1;
		if (isWeixin) {
			return true;
		} else {
			return false;
		}
	}
	return false;
}


/**
 * 手机号码
 * @param {*} s
 */
function isMobile(s) {
	return /^1[0-9]{10}$/.test(s)
}

function getQueryObjH5(url) {
	if (!url) {
		url = window.location.href;
	}
	var reg_url = /^[^\?]+\?([\w\W]+)$/,
		reg_para = /([^&=]+)=([\w\W]*?)(&|$)/g, //g is very important
		arr_url = reg_url.exec(url),
		ret = {};
	if (arr_url && arr_url[1]) {
		var str_para = arr_url[1],
			result;
		while ((result = reg_para.exec(str_para)) != null) {
			ret[result[1]] = decodeURIComponent(result[2].replace("#", ""));
		}
	}
	return ret;
}

function getNow() {
	return moment().format("YYYY-MM-DD HH:mm:ss");
}

function getDate() {
	return moment().format("YYYY-MM-DD");
}

function getGUID() {
	function S4() {
		return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
	}
	return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}

function replaceHerfUrl(paramObj, url = window.location.href) {
	const urlInfo = new URL(url);
	Object.keys(paramObj).forEach(key => urlInfo.searchParams.set(key, paramObj[key]));
	let herf = urlInfo.href;
	window.history.replaceState(null, null, herf);
}

/**
 * @description: 记录百度事件 https://tongji.baidu.com/web/help/article?id=236&type=0
 * @param {eventName} 事件名称 比如打电话 关单
 * @param {eventRemark} 事件备注  比如 首页底部打电话按钮触发
 * @example this.$util.baiduEvent('客户搜索','首页顶部客户搜索');
 */
function baiduEvent(eventName, pageUrl, eventRemark = '') {
	pageUrl = pageUrl || (window.location.pathname + window.location.search);
	// pageUrl= new URL(pageUrl,window.location.origin);
	// pageUrl=pageUrl.pathname;
	const type = getApp().globalData.userInfo ? getApp().globalData.userInfo.wxUserInfoMobilePhone : '未登录';
	_hmt.push(['_trackEvent', pageUrl, type, eventName, eventRemark]);
}

/**
 * @description: 用于发送某个指定URL的PV统计请求  https://tongji.baidu.com/web/help/article?id=235&type=0
 * @param {pageUrl} 页面的URl
 * @example this.$util.baiduPageView();
 */
function baiduPageView(pageUrl) {
	let userInfo = getApp().globalData.userInfo;
	if (userInfo) {
		// 加上storeId
		pageUrl = `${pageUrl}?storeId=${userInfo.currentStoreId}`
		_hmt.push(['_setAutoPageview', false]);
		_hmt.push(['_trackPageview', pageUrl]);
	}
}

function wgs84togcj02(lng, lat) {
	// 定义一些常量
	var PI = 3.1415926535897932384626;
	var a = 6378245.0;
	var ee = 0.00669342162296594323;

	var lat = +lat;
	var lng = +lng;

	// 判断是否在国内，不在国内则不做偏移
	if (!(lng > 73.66 && lng < 135.05 && lat > 3.86 && lat < 53.55)) {
		return [lng, lat]
	} else {
		// 转换lat
		var dlatplng = lng - 105.0,
			dlatplat = lat - 35.0;
		var dlat = -100.0 + 2.0 * dlatplng + 3.0 * dlatplat + 0.2 * dlatplat * dlatplat + 0.1 * dlatplng * dlatplat +
			0.2 * Math.sqrt(Math.abs(dlatplng));
		dlat += (20.0 * Math.sin(6.0 * dlatplng * PI) + 20.0 * Math.sin(2.0 * dlatplng * PI)) * 2.0 / 3.0;
		dlat += (20.0 * Math.sin(dlatplat * PI) + 40.0 * Math.sin(dlatplat / 3.0 * PI)) * 2.0 / 3.0;
		dlat += (160.0 * Math.sin(dlatplat / 12.0 * PI) + 320 * Math.sin(dlatplat * PI / 30.0)) * 2.0 / 3.0;

		// 转换lng
		var dlngplng = lng - 105.0,
			dlngplat = lat - 35.0;
		var dlng = 300.0 + dlngplng + 2.0 * dlngplat + 0.1 * dlngplng * dlngplng + 0.1 * dlngplng * dlngplat + 0.1 *
			Math.sqrt(Math.abs(dlngplng));
		dlng += (20.0 * Math.sin(6.0 * dlngplng * PI) + 20.0 * Math.sin(2.0 * dlngplng * PI)) * 2.0 / 3.0;
		dlng += (20.0 * Math.sin(dlngplng * PI) + 40.0 * Math.sin(dlngplng / 3.0 * PI)) * 2.0 / 3.0;
		dlng += (150.0 * Math.sin(dlngplng / 12.0 * PI) + 300.0 * Math.sin(dlngplng / 30.0 * PI)) * 2.0 / 3.0;

		var radlat = lat / 180.0 * PI;
		var magic = Math.sin(radlat);
		magic = 1 - ee * magic * magic;
		var sqrtmagic = Math.sqrt(magic);
		dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI);
		dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI);
		var mglat = lat + dlat;
		var mglng = lng + dlng;

		return [mglng, mglat]
	}
}

/**
 * 处理富文本里的图片宽度自适应
 * 1.去掉img、video标签里的style、width、height属性
 * 2.修改所有style里的width属性为max-width:100%
 * 3.img、video标签添加style属性：max-width:100%;height:auto
 * 4.去掉<br/>标签
 * @param html
 * @return string
 */
function formatRichText(html) {
	// 去掉img标签里的style、width、height属性
	let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
		match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
		match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
		match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
		return match;
	});

	// 去掉video标签里的style、width、height属性
	newContent = html.replace(/<video[^>]*>/gi, function(match, capture) {
		match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
		match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
		match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
		return match;
	});
	// 修改所有style里的width属性为max-width:100%
	// 去掉所有style里的font-size属性
	newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {
		match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
		match = match.replace(/font-size:[^;]+;/gi, '');
		return match;
	});
	// 去掉<br/>标签
	newContent = newContent.replace(/<br[^>]*\/>/gi, '');
	// img标签添加style属性：max-width:100%;height:auto
	newContent = newContent.replace(/\<img/gi,
		'<img style="max-width:100%;height:auto;display:block;margin:0px auto;"');
	// video标签添加style属性：max-width:100%;height:auto
	newContent = newContent.replace(/\<video/gi,
		'<video style="max-width:100%;height:auto;display:block;margin:0px auto;"');
	newContent = newContent.replace(/\<section/gi,
		'<section style="max-width:100%;height:auto;display:block;margin:0px auto;"');
	newContent = parseHtml(newContent);
	return newContent;
}

//退出小程序
function exitApp(res) {
	wx.exitMiniProgram({
		success() {
			res && res();
		}
	})
}


function copyText(content) {
	uni.setClipboardData({
		data: content,
		showToast: false
	});
	if (content) {
		uni.showToast({
			title: '复制成功',
			icon: 'success',
			duration: 2000
		});
	}
}

/**
 * @description: 节流函数：规定一个单位时间，在这个单位时间内，只能有一次触发事件的回调函数执行
 * @param {Function} fn 要执行的函数
 * @param {Number} gapTime  单位时间
 */
function throttle(fn, delay = 500) {
	let timer = true;
	return function(args) {
		let that = this;
		let _args = arguments;
		if (!timer) {
			return false;
		}
		timer = false;
		setTimeout(() => {
			fn.apply(that, _args);
			timer = true;
		}, delay);
	}
}


export default {
	urlEncode,
	null2str,
	getCurrentPageUrl,
	getCurrentPageUrlAndArgs,
	isChgForWatch,
	getQueryObj,
	isWxBrowser,
	isMobile,
	showImg,
	calAnimalSign,
	calStar,
	calAge,
	getPrePageObj,
	deepCopy,
	getQueryObjH5,
	getNow,
	getGUID,
	getDistanceKm,
	getDate,
	replaceHerfUrl,
	baiduEvent,
	wgs84togcj02,
	formatRichText,
	parseHtml,
	wxCanMove,
	isIos,
	isAndriod,
	exitApp,
	copyText,
	throttle
}